//
//  UIImageView+RoundImage.m
//  beichoo_N_ios
//
//  Created by fanfan on 2017/9/8.
//  Copyright © 2017年 陈健. All rights reserved.
//

#import "UIImageView+RoundImage.h"
#import "objc/runtime.h"
#import "SDImageCache.h"
#import "SDWebImageManager.h"
#import <YYWebImage/YYWebImage.h>
#import "UIColor+Expand.h"
static char imageURLKey;

@implementation UIImageView (RoundImage)

- (void)ff_setImageUrl:(NSURL *)url
           placeholder:(UIImage *)placeholder
                  size:(CGSize )size
          cornerRadius:(CGFloat)radius
                 isFit:(BOOL)isfit {
    [self ff_setImageUrl:url
             placeholder:placeholder
                    size:size
            cornerRadius:radius
                 corners:UIRectCornerAllCorners
             borderWidth:0
             borderColor:nil
          borderLineJoin:kCGLineJoinMiter
                   isFit:YES];
}

- (void)ff_setImageUrl:(NSURL *)url
           placeholder:(UIImage *)placeholder
                  size:(CGSize )size
          cornerRadius:(CGFloat)radius {
    [self ff_setImageUrl:url
             placeholder:placeholder
                    size:size
            cornerRadius:radius
             borderWidth:0
             borderColor:nil];
}

- (void)ff_setImageUrl:(NSURL *)url
           placeholder:(UIImage *)placeholder
                  size:(CGSize )size
          cornerRadius:(CGFloat)radius
           borderWidth:(CGFloat)borderWidth
           borderColor:(NSString *)borderColor {
    [self ff_setImageUrl:url
             placeholder:placeholder
                    size:size
            cornerRadius:radius
                 corners:UIRectCornerAllCorners
             borderWidth:borderWidth
             borderColor:borderColor];
}

- (void)ff_setImageUrl:(NSURL *)url
           placeholder:(UIImage *)placeholder
                  size:(CGSize )size
          cornerRadius:(CGFloat)radius
               corners:(UIRectCorner)corners
           borderWidth:(CGFloat)borderWidth
           borderColor:(NSString *)borderColor {
    [self ff_setImageUrl:url
             placeholder:placeholder
                    size:size
            cornerRadius:radius
                 corners:corners
             borderWidth:borderWidth
             borderColor:borderColor
          borderLineJoin:kCGLineJoinMiter
                   isFit:NO];
}

- (void)ff_setImageUrl:(NSURL *)url
           placeholder:(UIImage *)placeholder
                  size:(CGSize )size
          cornerRadius:(CGFloat)radius
               corners:(UIRectCorner)corners
           borderWidth:(CGFloat)borderWidth
           borderColor:(NSString *)borderColor
        borderLineJoin:(CGLineJoin)borderLineJoin
                 isFit:(BOOL)isFit{
    __block UIImage *resutImage;

    NSString *urlConvert = [[[SDWebImageManager sharedManager] cacheKeyForURL:url] componentsSeparatedByString:@"?"][0];


    if(borderColor == nil) {
        borderColor = @"#333333";
    }
    NSString *urlStr = urlConvert;
    NSString *sizeStr = NSStringFromCGSize(size);
    NSString *radiusStr = [NSString stringWithFormat:@"%f",radius];
    NSString *cornersStr = [NSString stringWithFormat:@"%lu",(unsigned long)corners];
    NSString *borderWidthStr = [NSString stringWithFormat:@"%f",borderWidth];
    NSString *borderColorStr = borderColor;
    NSString *borderLineStr = [NSString stringWithFormat:@"%d",borderLineJoin];

    NSString *key = [NSString stringWithFormat:@"%@%@%@%@%@%@%@",urlStr,sizeStr,radiusStr,cornersStr,borderWidthStr,borderColorStr,borderLineStr];

    objc_setAssociatedObject(self, &imageURLKey, key, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    
    [[SDImageCache sharedImageCache] queryCacheOperationForKey:key done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
        
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = image;
            });
        } else {
            if (placeholder == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.image = placeholder;
                });
            }
            
            
            [[SDWebImageManager sharedManager] loadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    
                    dispatch_async(globalQueue, ^{
                        resutImage = image;
                        CGFloat scale = resutImage.scale;
                        if(scale!=[UIScreen mainScreen].scale) {
                            resutImage = [[UIImage alloc]initWithCGImage:resutImage.CGImage scale:[UIScreen mainScreen].scale orientation:resutImage.imageOrientation];
                        }
                        if (isFit) {
                            resutImage = [resutImage yy_imageByResizeToSize:size contentMode:UIViewContentModeScaleAspectFit];
                        }
                        else {
                            resutImage = [resutImage yy_imageByResizeToSize:size contentMode:UIViewContentModeScaleAspectFill];
                        }
                        
                        resutImage = [resutImage yy_imageByRoundCornerRadius:radius corners:corners borderWidth:borderWidth borderColor:[UIColor colorWithHexString:borderColor] borderLineJoin:borderLineJoin];
                        
                        [[SDImageCache sharedImageCache]storeImage:resutImage forKey:key completion:nil];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSString *tempKey = objc_getAssociatedObject(self, &imageURLKey);
                            if([tempKey isEqualToString:key]) {
                                self.image = resutImage;
                            }
                        });
                        
                    });
                }else {
                    if(placeholder!= nil) {
                        self.image = placeholder;
                    }
                }
            }];
        }
            
    }];
}
@end


